import axios from 'axios'
import store from '../store/index.js'

// 创建axios实例
const service = axios.create({
	baseURL: "https://www.xxley.com/music-api", // api 的 base_url
	timeout: 10000 // 请求超时时间
});

//设置默认请求头
axios.defaults.withCredentials = true
service.defaults.headers = {
	'Content-Type': "application/json"
};

// request拦截器
service.interceptors.request.use(
	config => {
		// 在发送请求之前做某件事
		if (store.state.user.token) {
			config.headers['token'] = store.state.user.token // 让每个请求携带自定义token 请根据实际情况自行修改
		}
		return config
	},
	error => {
		// Do something with request error
		uni.showToast({
			title: '',
			duration: 1500,
			icon: 'none',
			position: 'bottom'
		});
		return Promise.reject(error.data.error.message);
	}
);

// response 拦截器
service.interceptors.response.use(
	response => {
		// 根据响应码判断
		const result = response.data;
		if (result.code !== 200) {
			switch (result.code) {
				case 301: // 登录过期
					store.commit("REMOVE_LOGIN")
					uni.navigateTo({
						url: "/pages/subpages/account/login"
					})
					uni.showToast({
						title: result.msg,
						duration: 1500,
						icon: 'none',
						position: 'bottom'
					});
					break;
				default:
					uni.showToast({
						title: result.msg,
						duration: 1500,
						icon: 'none',
						position: 'bottom'
					});
					break;
			}
			return Promise.reject(result.resultDesc);
		}
		return result;
	},
	error => {
		uni.showToast({
			title: '网络请求错误',
			duration: 1500,
			icon: 'none',
			position: 'bottom'
		});
		return Promise.reject(error)
	}
);


//真机获取 解决app上adapter is not a function问题
axios.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}

export default service
